<!--
 * @FilePath: index.vue
 * @Author: 杜芬
 * @Date: 2023-12-04 09:37:38
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-12-04 09:55:54
 * Copyright: 2023 xxxTech CO.,LTD. All Rights Reserved.
 * @Descripttion: 页面
-->
<template>
  <!-- 购物车2 -->
  <div id="huo">
    <h2>购物车</h2>
    <ul id="list">
      <li v-for="item in myList" :key="item.id">
        <input type="button" value="-" @click="sub(item)" />
        <strong>{{ item.number }}</strong>
        <input type="button" value="+" @click="add(item)" />
        单价：<em>{{ item.price }}</em> 小计：<span>{{ item.number * item.price }}</span>
      </li>
    </ul>
    <p id="p">
      总价：<strong style="margin-right: 20px">{{ total }}元</strong>
      <!-- 最贵的单价是：<em>{{ bestValue }}元</em> -->
    </p>
  </div>
</template>
<script>
export default {
  data() {
    return {
      myList: [
        {
          number: 0,
          id: 0,
          price: 23,
        },
        {
          number: 0,
          price: 14.5,
          id: 1,
        },
        {
          number: 1,
          price: 8,
          id: 2,
        },
        {
          number: 0,
          price: 20,
          id: 3,
        },
      ],
      total: 0, //总价
      bestValue: 0, //最贵单价
    };
  },
  created() {
    this.count();
  },
  methods: {
    //相减
    sub(item) {
      item.number--;
      if (item.number <= 0) {
        item.number = 0;
      }
      this.count();
    },
    //相加
    add(item) {
      item.number++;
      this.count();
    },
    // 总数
    count() {
      var totalPrice = 0; //临时总价
      this.myList.forEach(function (val, index) {
        totalPrice += val.number * val.price; //累计总价
      });
      this.total = parseFloat(totalPrice);
    },
    // sub: function (item) {
    //   item.number--;
    //   if (item.number <= 0) {
    //     item.number = 0;
    //   }
    //   this.count();
    // },
    //相加
    // add: function (item) {
    //   item.number++;
    //   this.count();
    // },
    // count: function () {
    //   var totalPrice = 0; //临时总价
    //   var best = 0; //临时最大单价
    //   this.myList.forEach(function (val, index) {
    //     totalPrice += val.number * val.price; //累计总价
    //     // 判断最大单价
    //     if (val.price > best && val.number > 0) {
    //       best = val.price;
    //     }
    //   });
    //   this.total = parseFloat(totalPrice);
    //   this.bestValue = parseFloat(best);
    // },
  },
};
</script>
